package com.digitalchina.lxnsy.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.NonNull;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.activity.old.AddFarmingRecordActivityV2;
import com.digitalchina.lxnsy.api.BusinessPlan;
import com.digitalchina.lxnsy.base.BaseV4Fragment;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.OperationRecordsVO;
import com.digitalchina.lxnsy.interfaces.IMyNhbPos;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.Utils;
import com.digitalchina.lxnsy.viewholder.FarmingRecordFertilizerHolderV3;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

import static android.app.Activity.RESULT_OK;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.fragment
 * 创建人：郑皓
 * 创建时间：2018/8/28 11:07
 * 修改备注：
 * ================================================
 */
public class PlanFarmingRecordFragment extends BaseV4Fragment implements RecyclerArrayAdapter.OnLoadMoreListener, SwipeRefreshLayout.OnRefreshListener, IMyNhbPos {
    @Bind(R.id.recycler_view)
    EasyRecyclerView recyclerView;
    @Bind(R.id.iv_add)
    ImageView ivAdd;

    private String planId = ""; // 生产计划ID

    private RecyclerArrayAdapter adapter;
    private int page = 1;
    private int limit = 10;
//    private List<FarmingRecordVO> voList = new ArrayList<>();
    private List<OperationRecordsVO> voList = new ArrayList<>();


    @Override
    public View setRootView() {
        return inflate(R.layout.fragment_farming_record_list);
    }

    @Override
    public void initMember() {
        planId = getArguments().getString("planId");

        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        recyclerView.addItemDecoration(Utils.setDividerDecoration(getActivity(), 1, 0, 0));

        recyclerView.setAdapterWithProgress(adapter = new RecyclerArrayAdapter(getActivity()) {
            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                return new FarmingRecordFertilizerHolderV3(parent, PlanFarmingRecordFragment.this);
            }
        });

        onRefresh();

    }


    @Override
    public void addListener() {

        recyclerView.setRefreshListener(this);

        adapter.setMore(R.layout.view_more, this);

        adapter.setNoMore(R.layout.view_nomore);

        adapter.setError(R.layout.view_error, new RecyclerArrayAdapter.OnErrorListener() {
            @Override
            public void onErrorShow() {
                adapter.resumeMore();
            }

            @Override
            public void onErrorClick() {
                adapter.resumeMore();
            }
        });


        ivAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), AddFarmingRecordActivityV2.class);
                intent.putExtra("productionId", planId);
                startActivityForResult(intent, 99);
            }
        });
    }

    public void updatePlanId(String planId) {
        this.planId = planId;
        onRefresh();
    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                if (recyclerView == null) {
                    return;
                }
                if (recyclerView.getSwipeToRefresh().isRefreshing())
                    recyclerView.setRefreshing(false);

                switch (msg.what) {
                    case MSG.MSG_FARMING_LIST_SUCCESS:
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_FARMING_LIST_FIELD:
                        if (adapter.getAllData().size() > 0)
                            adapter.pauseMore();
                        else
                            recyclerView.showEmpty();
                        break;
                    case MSG.MSG_FARMING_DELETE_SUCCESS:
                        showToast("删除成功");
                        onRefresh();
                        break;
                    case MSG.MSG_FARMING_DELETE_FIELD:
                        showToast(msg.obj.toString());
                        break;
                }
            }
        };
    }

    @Override
    public void callBack(Object object) {
        voList = FastJsonUtil.getListBean(object.toString(), "operationRecordsVOList", OperationRecordsVO.class);

        if (page == 1) { // 刷新
            adapter.clear();
        }

        adapter.addAll(voList);


        if (voList != null) {
            if (voList.size() < limit) {
                adapter.stopMore();
            }
        }
    }

    @Override
    public void rightOnClick() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onRefresh() {
        page = 1;
        BusinessPlan.farmingList(getActivity(), planId, page, limit, mHandler);
    }

    @Override
    public void onLoadMore() {
        if (voList != null && voList.size() >= limit) {
            BusinessPlan.farmingList(getActivity(), planId, page, limit, mHandler);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            onRefresh();
        }
    }

    @Override
    public void del(final int pos) {
        new MaterialDialog.Builder(getActivity())
                .title("提示")
                .content("确定要删除该条记录？")
                .positiveText("删除")
                .negativeText("取消")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        OperationRecordsVO vo = (OperationRecordsVO) adapter.getAllData().get(pos);
                        BusinessPlan.farmingDelete(getActivity(), vo.getId(), mHandler);
                    }
                })
                .show();
    }

    @Override
    public void edit(final int pos) {
        Intent intent = new Intent(getActivity(), AddFarmingRecordActivityV2.class);
        OperationRecordsVO vo = (OperationRecordsVO) adapter.getAllData().get(pos);
        intent.putExtra("OperationRecordsVO", (Serializable) vo);
        startActivityForResult(intent, 99);
    }
}
